import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

const store = new Vuex.Store({
  state: {
    token: uni.getStorageSync('token') || '', // 从本地存储读取 token
    userInfo: uni.getStorageSync('userInfo') || {}, // 从本地存储读取用户信息
  },
  mutations: {
    SET_TOKEN(state, token) {
      state.token = token;
      uni.setStorageSync('token', token); // 持久化存储
    },
    SET_USER_INFO(state, userInfo) {
      state.userInfo = userInfo;
      uni.setStorageSync('userInfo', userInfo); // 持久化存储
    },
    CLEAR_USER(state) {
      state.token = '';
      state.userInfo = {};
      uni.removeStorageSync('token');
      uni.removeStorageSync('userInfo');
    },
  },
  actions: {
    login({ commit }, { username, password }) {
      return new Promise((resolve, reject) => {
        // 假设请求登录接口
        import('../utils/request.js')
          .then((request) => {
            request
              .default.post('/login', { username, password })
              .then((res) => {
                const { token, userInfo } = res.data;
                commit('SET_TOKEN', token);
                commit('SET_USER_INFO', userInfo);
                resolve(res);
              })
              .catch((err) => {
                reject(err);
              });
          })
          .catch((error) => reject(error));
      });
    },
    logout({ commit }) {
      commit('CLEAR_USER');
    },
  },
});

export default store;